import { createRouter, createWebHistory } from 'vue-router'
import { getToken } from '../utils/cookie'
import { ElMessage } from 'element-plus'

// 路由配置
const routes = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('../views/Login.vue')
    },
    {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/layout',
        name: 'Layout',
        component: () => import('../views/Layout.vue'),
        redirect: '/layout/dashboard',
        children: [
            {
                path: 'dashboard',
                name: 'Dashboard',
                component: () => import('../views/Dashboard.vue'),
                meta: { title: '仪表板' }
            },
            {
                path: 'book',
                name: 'Book',
                component: () => import('../views/Book.vue'),
                meta: { title: '图书管理' }
            },
            {
                path: 'reader',
                name: 'Reader',
                component: () => import('../views/Reader.vue'),
                meta: { title: '读者管理' }
            },
            {
                path: 'user',
                name: 'User',
                component: () => import('../views/sysUser.vue'),
                meta: { title: '用户管理' }
            },
            {
                path: 'profile',
                name: 'profile',
                component: () => import('../components/Profile.vue'),
                meta: { title: '个人信息' }
            }
        ]
    },
    {
        path: '/:pathMatch(.*)*',
        name: '404',
        component: () => import('../components/404.vue')
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
    // 获取token
    const hasToken = getToken()
    
    if (hasToken) {
        // 已登录状态
        if (to.path === '/login') {
            // 如果已登录且要跳转的页面是登录页，则重定向到首页
            next({ path: '/layout' })
        } else {
            next()
        }
    } else {
        // 未登录状态
        if (to.path === '/login') {
            // 如果是登录页面，直接通过
            next()
        } else {
            // 其他页面重定向到登录页
            ElMessage.warning('请先登录')
            next({
                path: '/login',
                query: { redirect: to.fullPath }
            })
        }
    }
})

export default router
